<?php

use Curl\Curl;

class Request
{
    protected $reqBaseUrl;
    protected $reqCurl;
    protected $reqMethod;
    protected $reqErrorMessage;
    protected $reqErrorCode;

    const TIMEOUT         = 15;
    const TIMEOUT_CONNECT = 5;
    const RETRY           = 3;

    public function __construct($baseUrl = null)
    {
        $this->reqBaseUrl = $baseUrl;
        $this->reqCurl    = new Curl();
        $this->reqCurl->setOpts([
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);
        $this->reqCurl->setDefaultDecoder('json');
        $this->reqCurl->setConnectTimeout(self::TIMEOUT_CONNECT);
        $this->reqCurl->setTimeout(self::TIMEOUT);
        $this->reqCurl->setUserAgent(sprintf('PGC PHP/%s curl/%s', PHP_VERSION, curl_version()['version']));
        $this->reqCurl->errorFunction = function (Curl $curl) {
            throw new RuntimeException($curl->errorMessage, $curl->errorCode);
        };
    }

    public function get($uri, $data = [])
    {
        return $this->reqCurl->get($this->reqBaseUrl . $uri, $data);
    }

    public function post($uri, $data = [])
    {
        return $this->reqCurl->post($this->reqBaseUrl . $uri, $data, false);
    }

    public function put($uri, $data = [])
    {
        return $this->reqCurl->put($this->reqBaseUrl . $uri, $data);
    }

    public function __set($name, $value)
    {
        if (!property_exists($this, $name)) {
            $this->reqCurl->{$name} = $value;
        }
    }

    public function __get($name)
    {
        if (!property_exists($this, $name)) {
            return $this->reqCurl->{$name};
        }
        return $this->{$name};
    }

    public function __call($name, $arguments)
    {
        if (!method_exists($this, $name)) {
            return call_user_func([$this->reqCurl, $name], ...$arguments);
        }
        return call_user_func([$this, $name], ...$arguments);
    }
}
